import pickle

from Crypto.Cipher import AES

t = ('hello world', "nihao")
# plaintext = pickle.dumps(t)  # 将元组转换成字节
key = b'10234fgzsdce2345'


# print(plaintext)


def encrypt(key, message):
    plaintext = pickle.dumps(message)  # 将message的元组修改为字节类型
    cipher = AES.new(key, AES.MODE_GCM)  # 创建一个加密对象
    nonce = cipher.nonce  # 创建一次性数字，用于保证在密钥和明文相同的情况下，加密的结果不一致
    ciphertext, tag = cipher.encrypt_and_digest(plaintext)  # ciphertext是密文，tag是认证标签，保证密文的完整性和真实性
    return ciphertext, nonce, tag


b = b'5'


def decrypt(key, ciphertext, nonce, tag):
    cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
    t = cipher.decrypt(ciphertext)   # 解密，结果为字节
    plaintext = pickle.loads(t)  # 将解密后的明文修转化为元组
    try:
        cipher.verify(tag)
        return plaintext
    except ValueError:
        print("key is not valid")
        return False


test_enc, nonce, tag = encrypt(key, t)
pl = decrypt(key, test_enc, nonce, b)
print(type(pl))
# print(test_enc, nonce, tag)
# print(test_enc)
# print(test_enc[0])
# print(test_enc[1])
# print(test_enc[2])
# decrypt(key, test_enc[0], test_enc[1], test_enc[2])
